<template>
  <div class="semGoodsCouponSelect">
    <div class="tags-outer-block">
      <div class="tags-block" :class="{'is-full-screen': isFullScreen}">
        <el-tag
          v-for="(item, index) in selected"
          :key="index"
          :closable="!disabled"
          @close="$emit('remove', {value: item})">{{ generateSelectName(item) }}</el-tag>
      </div>
      <el-link class="full-screen-btn" :underline="false" @click="isFullScreen = !isFullScreen">
        <i v-if="isFullScreen" class="el-icon-bottom-left"></i>
        <i v-else class="el-icon-top-right"></i>
      </el-link>
    </div>
    <div class="table-block">
      <search-block type="flex">
        <el-form inline :model="model">
          <el-form-item label="名称:">
            <el-input v-model="model.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="货号:">
            <el-input v-model="model.productSn" clearable></el-input>
          </el-form-item>
          <el-form-item label="分类:">
            <el-cascader
              v-model="model.productCategoryId"
              clearable
              :options="goodsCate"
              :props="{
                label: 'name',
                value: 'id'
              }"></el-cascader>
          </el-form-item>
        </el-form>
        <div class="goods-buttons">
          <div class="el-button el-button--primary" @click="search">查询</div>
        </div>
      </search-block>
      <y-table
        ref="table"
        border
        @select="changeTableSelect"
        @select-all="changeTableSelect"
        @load-data="initTableSelect"
        :unable-select-all="!!disabled"
        :selectable="() => !disabled"
        pagination
        :selection="!selectSku"
        :getDataWay="getDataWay"
        :columns="columns">
        <el-table-column slot="SKU" label="选择SKU" align="center" header-align="center" min-width="80" v-if="selectSku">
          <template v-slot="{row}">
            <el-popover v-model="row.showPopover">
              <div :class="{'row-radio': !multiple, 'row-checkbox': multiple}">
                <el-checkbox
                  v-for="item in row.skuData"
                  :key="item.value"
                  :disabled="disabled"
                  style="display: block"
                  @change="() => changeSelect(row, item)"
                  v-model="item.checked">{{item.label}}</el-checkbox>
              </div>
              <div slot="reference" class="el-button el-button--primary el-button--mini" @click="initSelect(row)">sku</div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column slot="imgUrl" label="图标" align="center" header-align="center" min-width="120">
          <template v-slot="{row}">
            <img v-if="row.imgUrl" style="max-width: 100px" :src="generateMediaUrl({fileOpenUrl: row.imgUrl})"/>
          </template>
        </el-table-column>
        <el-table-column slot="name" label="商品名称/标题" align="center" header-align="center" min-width="300">
          <template v-slot="{row}">
            <div>{{row.name}}</div>
            <div>{{row.subTitle}}</div>
          </template>
        </el-table-column>
        <el-table-column slot="price" label="商品价格/货号" align="center" header-align="center" min-width="250">
          <template v-slot="{row}">
            <div>价格：{{generatePrice(row)}}</div>
            <div>货号：{{row.productSn}}</div>
          </template>
        </el-table-column>
      </y-table>
    </div>
  </div>
</template>

<script>
export default {
  name: "semGoodsCouponSelect",
  inject: ['generateMediaUrl'],
  props:{
    selected:{
      type: Array,
      default: () => []
    },
    multiple:{
      type: Boolean,
      default: true
    },
    goodsCate: Array,
    goodsMap: Object,
    goodsSkuMap: Object,
    disabled:{
      type: Boolean,
      default: false
    },
    selectSku:{//选sku还是选商品
      type: Boolean,
      default: true
    }
  },
  computed:{
    getDataWay(){
      return {
        dataType: 'url',
        data: this.$api.goods.goodsList,
        param: this.searchData
      }
    },
    searchData(){
      let obj = {...this.model};
      if(Array.isArray(obj.productCategoryId)){
        obj.productCategoryId = obj.productCategoryId.join('/');
      }
      return obj;
    }
  },
  data(){
    return{
      model:{
        name: '',
        productCategoryId: '',
        publishStatus: 1,
        tag: 0
      },
      columns: [{
        label: "选择sku",
        prop: "SKU",
        template: true
      },{
        label: "商品图标",
        prop: "imgUrl",
        template: true,
      },{
        label: "商品名称/标题",
        prop: "name",
        template: true
      },{
        label: "价格/货号",
        prop: "price",
        template: true
      }],
      isFullScreen: false,//最大化
    }
  },
  methods:{
    search(){
      this.$refs['table'].loadData(this.searchData);
    },
    generateSelectName(str){
      let [goodsId, skuId] = str.split('/');
      return this.selectSku ?
        (this.goodsMap[goodsId] ? this.goodsMap[goodsId] + '/' + (this.goodsSkuMap[skuId] || '') : ''):
          (this.goodsMap[goodsId] || '');
    },
    generatePrice(row){
      if(!row.minPrice && !row.maxPrice){
        return '无'
      }else if(!row.minPrice){
        return '￥' + row.maxPrice
      }else if(!row.maxPrice){
        return '￥' + row.minPrice
      }else{
        if(row.minPrice === row.maxPrice){
          return '￥' + row.minPrice
        }else{
          return '￥' + row.minPrice + '~￥' + row.maxPrice
        }
      }
    },
    async initSelect(row){
      //如果没加载sku列表，先加载列表
      if(!row.skuData || !row.skuData.length){
        let info = await this.initSku(row);
        this.$set(row, 'skuData', info.map(item => ({
          value: item.id,
          label: item.spData,
          checked: false
        })));
      }else{
        row.skuData.map(item => {
          this.$set(item, 'checked', false);
        })
      }
      let mySelect = this.selected.filter(str => str.startsWith(row.id + '/'));
      mySelect.map(str => {
        let sku = str.split('/').pop();
        let obj = row.skuData.find(item => item.value === sku);
        if(obj){
          this.$set(obj, 'checked', true);
        }
      })
      /*this.$nextTick(() => {
        this.$set(row, 'showPopover', true);
      })*/
    },
    initSku(row){
      return new Promise(resolve => {
        this.$yAxios({
          url: this.$api.goods.searchSku,
          data:{
            productId: row.id
          },
          loading: true
        }, info => {
          resolve(info.record || []);
        }, e => {
          resolve([]);
        });
      })
    },
    changeSelect(goodsObj, skuObj){
      this.goodsMap[goodsObj.id] = goodsObj.name;
      this.goodsSkuMap[skuObj.value] = skuObj.label;
      let event = skuObj.checked ? 'add' : 'remove';
      let emitObj = {
        value: goodsObj.id + '/' + skuObj.value,
        rootName: goodsObj.name,
        skuName: skuObj.label
      };
      this.$emit(event, emitObj);
      if(!this.multiple)goodsObj.showPopover = false;
    },
    changeTableSelect(selection){
      let value = selection.map(row => {
        this.goodsMap[row.id] = row.name;
        return row.id;
      })
      this.$emit('change', value);
    },
    initTableSelect(data, $table){
      data.map(row => {
        if(this.selected.indexOf(row.id) >= 0){
          $table.toggleRowSelection(row)
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.semGoodsCouponSelect{
  .tags-outer-block{
    width: 100%;
    border: @common-border;
    display: flex;
    .tags-block{
      width: calc(100% - 20px);
      border-right: @common-border;
      display: flex;
      align-items: center;
      height: 50px;
      overflow-x: auto;
      overflow-y: hidden;
      white-space: nowrap;
      padding: 2.5px 20px;
      position: relative;
      &.is-full-screen{
        //display: block;
        height: auto;
        min-height: 50px;
        overflow: visible;
        white-space: unset;
        flex-wrap: wrap;
      }
      >.el-tag{
        margin: 2.5px 5px;
      }
      >.full-screen-btn{
        align-self: flex-start;
      }
    }
  }
  .table-block{
    padding: 20px;
    border: @common-border;
    border-top: none;
  }
}
.row-radio{
  /deep/ .el-checkbox__inner{
    border-radius: 10px;
  }
}
</style>